<template>
    <el-upload
        class="avatar-uploader"
        action=""
        accept=".jpg, .jpeg, .png"
        :http-request="upload"
        :show-file-list="false"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload">
        <img v-if="value" :src="value" class="avatar">
        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>
</template>

<script>
import COS from 'cos-js-sdk-v5'

export default {
    name: 'ImgUpload',
    props: {
        value: [String, null]
    },
    data () {
        return {}
    },
    methods: {
        handleAvatarSuccess (res, file) {
            this.$emit('input', URL.createObjectURL(file.raw))
        },
        beforeAvatarUpload (file) {
            const isJPG = file.type === 'image/jpeg'
            const isPNG = file.type === 'image/png'
            const isLt2M = file.size / 1024 / 1024 < 2

            if (!(isJPG || isPNG)) {
                this.$message.error('上传头像图片只能是 JPG 或 PNG 格式！')
            }
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 2MB!')
            }
            return (isJPG || isPNG) && isLt2M
        },
        upload (e) {
            const cos = new COS({
                SecretId: 'AKIDTlriKg1EF1Y2MRHOGvMl184ZruT3mLft',
                SecretKey: '70e5OUP6c3MXWSCi060g7KJ5dw3wkNuF'
            }) // 完成cos对象的初始化
            cos.putObject({
                Bucket: 'web90-1258898967', // 存储桶名称
                Region: 'ap-nanjing', // 地域名称
                Key: e.file.name, // 文件名称
                StorageClass: 'STANDARD', // 固定值
                Body: e.file // 文件对象
            }, (err, data) => {
                if (data.statusCode === 200 && data.Location) {
                    // 拿到了腾讯云返回的地址
                    // 通过input自定义事件将地址传出去
                    this.$emit('input', 'http://' + data.Location) // 将地址返回了
                } else {
                    this.$message.error(err.Message) // 上传失败提示消息
                }
            })
        }
    }
}
</script>

<style scoped lang="scss">
.avatar-uploader {
    ::v-deep .el-upload {
        border: 1px dashed #D9D9D9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;

        .avatar-uploader-icon {
            font-size: 28px;
            color: #8C939D;
            width: 178px;
            height: 178px;
            line-height: 178px;
            text-align: center;
        }

        .avatar {
            width: 178px;
            height: 178px;
            display: block;
        }

        &:hover {
            border-color: #409EFF;
        }
    }
}
</style>
